﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;

namespace WpfPdfReader
{
    /// <summary>
    /// WindowProgressBar.xaml 的交互逻辑
    /// </summary>
    public partial class WindowProgressBar : Window
    {
        public WindowProgressBar()
        {
            InitializeComponent();
        }

        private Action<int,Action<string>> ProcessFunc = null;
        
        public void Init(int maxinum, Action<int, Action<string>> func)
        {
            this.progressBar.Minimum = 0;
            this.progressBar.Maximum = maxinum;
            this.ProcessFunc = func;
        }


        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            BeginWork();
        }

        private void UpdateStatus(string statusMsg)
        {
            this.status.Text = statusMsg;
        }

        private delegate void UpdateProgressBarDelegate(System.Windows.DependencyProperty dp, Object value);
        private void BeginWork()
        {
            Thread thread = new Thread(new ThreadStart(() =>
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(progressBar.SetValue);
                    for (int i = 0; i < this.progressBar.Maximum; i++)
                    {
                        if (this.ProcessFunc != null)
                        {
                            this.ProcessFunc(i, UpdateStatus);
                        }
                        this.progressBar.Dispatcher.Invoke(
                          updatePbDelegate,
                          System.Windows.Threading.DispatcherPriority.Background,
                          new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(i + 1) }
                          );
                    }

                    this.Close();
                }));
            }));
            thread.Start();
        }
    }
}
